home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Java Primer Plus
/
Java Primer Plus (Waite Group Proess)(1996).iso
/
chapter13
/
SingleBuff.java
< prev
Wrap
Text File
|
1995-12-31
|
3KB
|
91 lines
/* Single buffering example */
import java.awt.*;
public class SingleBuff extends java.applet.Applet implements Runnable {
/* Variables to hold the dimensions of the applet */
protected int XRES,YRES;
/* Width, height, and grid spacing */
protected int w=100,h=100,gw=10;
/* X, Y, and previous Y positions */
protected int x,y=1,oldy=1;
Thread MyThread; // main thread for repaints
/* lx..lw are for concentric circles */
public int lx,ly,lh,lw;
public Rectangle AppBorder;
/* The applet init method */
public void init() {
AppBorder = bounds(); // get current applet
XRES = AppBorder.width;
YRES = AppBorder.height;
x = XRES/2-w/2; // center the image
}
/* The paint method */
public void paint(Graphics g) {
g.setColor(Color.lightGray); // background color
g.fillRect(x,oldy,w+1,h+1); // cover up last box drawn
oldy=y; // remember y for the next coverup
/* draw background pattern */
for(int gc=0;gc<XRES;gc+=gw) {
g.setColor(Color.gray); // color of gridlines
g.drawLine(gc,0,gc,YRES); // draw vertical lines
g.drawLine(0,gc,XRES,gc); // draw horizontal lines
g.setColor(Color.yellow); // set color to yellow
g.drawLine(gc,0,0,gc); // draw diags
g.setColor(Color.blue); // set color to blue
g.drawLine(XRES-gc,0,XRES,gc); // draw diags
}
g.setColor(Color.lightGray); // background color
g.fillRect(0,0,100,20); // clear box for title
g.setColor(Color.red); // set color to red
g.drawString("SingleBuffer",0,10);
g.fillRect(x,y,w,h); // draw red square
g.setColor(Color.blue);
int l=0;
for (int lh=h;lh>0;l+=4,lh-=8)
g.drawOval(x+l,y+l,lh,lh);
}
public void start() {
if(MyThread==null) { // start a new thread if not already running
MyThread = new Thread(this);
MyThread.start();
}
}
public void update(Graphics g) {
// override update to avoid clearing the screen
paint(g);
}
public void stop() {
if (MyThread != null) MyThread.stop();
MyThread = null; //kill thread when applet is stopped
}
public void run() { // the run loop.
int yd = 1;
while(true) {
y += yd;
if (y<=1 || y >= YRES) yd = -yd;
try {Thread.sleep(5);} catch(InterruptedException e){}
this.repaint(); //redraw the screen
}
}
}